package com.jjlin.chapter_2;

import java.util.*;
public class CD138{
    public static class Node{
        public int val;
        public Node next;
        public Node(int data){
            this.val = data;
        }
    }

    public static Node createNodeList(int[] nums){
        if(nums == null || nums.length < 1)
            return null;
        Node head = new Node(nums[0]);
        Node pre = head;
        for(int i = 1; i < nums.length; i++){
            Node cur = new Node(nums[i]);
            pre.next = cur;
            pre = cur;
        }
        return head;
    }

    public static void printNodeList(Node head){
        Node cur = head;
        while(cur != null){
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }

    //解法1：利用栈来删除指定值的节点,时间复杂度为O(N)，空间复杂度为O(N)
    public static void removeValue(Node head, int value){
        Stack<Node> stack = new Stack<>();
        while(head != null){
            if(head.val != value)
                stack.push(head);
            head = head.next;
        }
        while(!stack.isEmpty()){//将节点重新连接
            stack.peek().next = head;
            head = stack.pop();
        }
    }

    //解法2：直接调整链表，时间复杂度为O(N),空间复杂度为O(1)
    public static void removeValue1(Node head, int value){
        while(head != null){//寻找第一个值不为value的节点
            if(head.val != value)
                break;
            head = head.next;
        }
        Node cur = head;
        Node pre = head;
        while(cur != null){
            if(cur.val != value){
                pre = cur;
            }else{
                pre.next = cur.next;//删除指定值的节点
            }
            cur = cur.next;
        }
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] nums = new int[n];
        for(int i = 0; i < n; i++)
            nums[i] = sc.nextInt();
        int value = sc.nextInt();
        Node head = createNodeList(nums);
        removeValue(head, value);
        printNodeList(head);
    }
}

